<script lang="ts" setup>
import { reactive, ref, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { User,Lock } from '@element-plus/icons-vue'
import request from '../api/index.js'
import {login} from "../api/login.js"
import { ElMessage } from 'element-plus'
import {CONFIG} from '../config/index.js'

const loginInfo = reactive({
  username: "",
  password: "",
})
const loginRef = ref()
const rules = reactive({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
})

let loginButtonDisabled = ref(true)

// 监听username和password输入情况
watch([()=>loginInfo.username,()=>loginInfo.password],()=>{
  loginRef.value.validate((valid)=>{
    if(valid) {
      // 表单校验成功
      loginButtonDisabled.value = false
    }else{
      loginButtonDisabled.value = true
    }
  })
})


// 实现登录接口
const submitForm = () => {
  console.log(loginInfo)
  login(loginInfo.username,loginInfo.password).then((response)=>{
    console.log("登录response:", response)
    if (response.data.status = 200){
      // token 保存到浏览器
      const token = response.data.data.token
      window.localStorage.setItem(CONFIG.TOKEN_NAME, token)
      // 添加登录提醒
      ElMessage({
        message: response.data.message,
        type: 'success',
      })
    }
  })
}

</script>

<template>
  <el-card class="box-card">
    <!-- <div v-for="o in 4" :key="o" class="text item">{{ 'List item ' + o }}</div> -->
    <h2>后台管理系统</h2>
    <el-form
    ref="loginRef"
    :model="loginInfo"
    status-icon
    :rules="rules"
  >
    <el-form-item  prop="username">
      <el-input clearable :prefix-icon="User" placeholder="用户名" v-model="loginInfo.username" />
    </el-form-item>

    <el-form-item prop="password">
      <el-input show-password :prefix-icon="Lock" placeholder="密码" v-model="loginInfo.password" type="password" autocomplete="off" />
    </el-form-item>


    <el-form-item>
      <el-button type="primary" :disabled="loginButtonDisabled" @click="submitForm()"
        >登录</el-button
      >
    </el-form-item>
  </el-form>
  </el-card>

</template>
<style scoped>
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.box-card {
  width: 480px;
}
</style>